<template>
  <div class="experimentList">
    <div class="table">
      <div class="head" style="margin-top:-10px">
        <span class="title">实验列表</span>
        <el-button
        
          icon="el-icon-refresh"
          class="refreshBtn"
          size="small"
          type="primary"
          round
          v-debounce="getTableData"
          >刷新</el-button
        >
      </div>
      <div class="content">
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          fit
          stripe
          highlight-current-row
          width="100%"
        >
          <template slot="empty">
            <span>实验数据为空</span>
          </template>
          <el-table-column prop="id" label="Id" width="50px" />
          <el-table-column
            prop="name"
            align="center"
            label="实验名称"
            
          />
          <el-table-column
            prop="creator"
            align="center"
            label="创建人"
            width="130px"
          />
          <el-table-column
            prop="creatorSchool"
            align="center"
            label="创建学校"
            width="150px"
          />

          <el-table-column
            v-if="userInfo.roleName != 'schoolAdmin' && userInfo.roleName != 'teacher'"

            prop="schoolNames"
            align="center"
            label="关联该实验的学校名字"
            width="400px"
          >
            <template v-slot="{row}">
              <el-tag style="margin-left:0.01rem" v-for="item in row.schoolNames" :key="item">{{item}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            v-if="userInfo.roleName == 'schoolAdmin'"
            align="center"
            label="时间限制"
            width="320px"
          >
            <template v-slot="{ row }">
              <span v-if="row.startTime">
                {{ row.startTime }}&nbsp;至&nbsp; {{ row.endTime }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            align="center"
            label="状态"
            v-if="userInfo.roleName == 'schoolAdmin'"
            width="100px"
          >
            <template v-slot="{ row }">
              <el-tag v-if="row.status == 'DISABLE'" type="danger"  class="close">禁用</el-tag>
              <el-tag v-else type="success"  class="open" >开放</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="调整顺序" align="center" v-if="userInfo.roleName == 'schoolAdmin'" >
          <template slot-scope="scope">
            <el-button size="mini" type='text'    @click.stop="sortUp(scope.$index, scope.row)">向上↑ </el-button>
            <el-button size="mini" type='text'    @click.stop="sortDown(scope.$index, scope.row)">向下↓</el-button>
          </template>
        </el-table-column>


          <el-table-column label="操作" align="center" width="480px">
            <template slot-scope="{ row }">
            <el-button class="btn_primary" size="medium" icon="el-icon-view" @click="showExperiment(row)">预览</el-button>
            <el-popover placement="top" width="380" trigger="click" >
            <p>{{row.note}}</p>
                  <el-button slot="reference" size="medium" type="primary" icon="el-icon-notebook-2" class="btn_primary"
                    >备注</el-button
                  >
                </el-popover>
              <template v-if="userInfo.roleName == 'schoolAdmin'">
                <el-popover placement="top" width="480" trigger="click">
                  <el-date-picker
                    v-model="row.limitDateTime"
                    type="datetimerange"
                    range-separator="至"
                    size="small"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                  <el-button
                    v-if="userInfo.roleName == 'schoolAdmin'"
                    style="margin-left:5px"
                    type="primary"
                    size="mini"
                    :loading="row.editTimeLoading"
                    @click="editTimeLimit(row)"
                    >确定</el-button
                  >
                  <el-button slot="reference" size="medium" type="primary" icon="el-icon-time" class="btn_primary"
                    >时间</el-button
                  >
                </el-popover>
                <el-button
                  class="btn_success"
                  v-if="row.status == 'DISABLE'"
                   size="medium"
                  icon="el-icon-lock"
                  type="success"
                  :loading="row.statusLoading"
                  @click="editStatus(row, 'ENABLE')"
                  >开放</el-button
                >
                <el-button
                  class="btn_danger"
                  v-else
                  icon="el-icon-unlock"
                  type="danger"
                  size="medium"
                  :loading="row.statusLoading"
                  @click="editStatus(row, 'DISABLE')"
                  >禁用</el-button
                >
              </template>

              <el-button  
              size="medium" 
              @click="editExperiment(row)" 
              type="primary" 
              icon="el-icon-edit-outline"
              class="btn_primary"
                >编辑</el-button
              >
             <template v-if="row.creatorSchool == userInfo.schoolName">
              <el-popconfirm
                icon="el-icon-info"
                icon-color="red"
                title="确定删除这个实验吗？"
                @confirm="() => delExperiment(row)"
                
              >
                <el-button
                  size="medium"
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  :loading="row.delLoading"
                  class="btn_danger"
                  >删除</el-button
                >
              </el-popconfirm>
             </template>

            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-show="total > pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top:20px"
        >
        </el-pagination>
      </div>
      <el-dialog title="预览" :visible.sync="dialogVisible" width="900px" class="connect">
          <div class="container">
            <h2>{{experiment.name}}</h2>

            <div class="content">
              <div class="box">
                <el-table v-loading="dialogLoading" :data="this.experiment.questions" border fit stripe
                  highlight-current-row width="100%">
                  <template slot="empty">
                    <span>实验数据为空</span>
                  </template>
                  <el-table-column type="expand">
             <template slot-scope="props">
             <program-detail :question="props.row"></program-detail>
             </template>
          </el-table-column>
                  <el-table-column prop="title" align="center" label="题目" width="400px" />
                  <el-table-column prop="level" align="center" label="难度" width="155px">
                    <template v-slot="{ row }">
                      {{ levelChange(row.level) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="tags" align="center" label="知识点" width="300px">
                    <template v-slot="{ row }">
                      <el-tag v-for="item in row.tags" :key="item.index">{{ item.name }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>  
          </div>
        </el-dialog>
 
    </div>
  </div>
</template>

<script>
import {
  getExperimentByexperimentId,
  getExperimentBySchool,
  delExperiment,
  setExperimentStatus,
  setExperimentDateTime,
  getAllExperiment,
  sortExperiment
} from "@/api/experiment.js";
import programDetail from "@/components/programDetail.vue";
export default {
  components: {
    programDetail,
  },
  name:"experimentList",
  data() {
    return {
      dialogVisible: false,
      dialogLoading: false,
      tableLoading: false, //实验列表加载
      editTimeLoading: false, 
      listLoading: false, //关联实验列表加载
      dialogTableData: [],//关联实验列表
      userInfo: {},
      tableData: [],
      total: 0,
      isLink:false,  //是否进行了关联
      first:true,  //是否第一次进入
      pageSize: 10,
      currentPage: 1,
      experiment: {
        name: null,
        questions: null
      }
        
       
    };
  },
  //获取用户信息并获取列表
  created() {
    this.userInfo = JSON.parse(localStorage.getItem("user"));
    //console.log(this.userInfo);
    this.getTableData();
  },
  computed: {
      levelChange() {
        let levels = ["easy", "medium", "hard", "insuperable", "hell"];
        return val => {
          return levels[val];
        };
      }
    },
activated(){
  if(this.$route.params.mark==true){
    this.getTableData();
  }
},
  methods: {
    //切换开放和禁用状态
    editStatus(row, status) {
      row.statusLoading = true;
      let obj = {
        experimentId: row.id,
        schoolId: this.userInfo.schoolId,
        status: status
      };
      setExperimentStatus(obj)
        .then(res => {
          if (status == "DISABLE") {
            this.$message.success("已禁用"), (row.status = "DISABLE");
          } else {
            this.$message.success("已开放");
            row.status = "ENABLE";
          }
        })
        .finally(() => {
          row.statusLoading = false;
        });
    },
    //删除实验
    delExperiment(row) {
      row.delLoading = true;
      let obj = {
        experimentId: row.id,
        userId: this.userInfo.userId
      };
      //console.log(obj.userId);
      delExperiment(obj)
        .then(res => {
          this.$message.success("删除成功");
          this.getTableData();
        })
        .finally(() => {
          row.delLoading = false;
              this.isLink=true;
        });
    },
  
    //设置事件限制
    editTimeLimit(row) {
      console.log(row);
      row.editTimeLoading = true;
      let obj = {
        experimentId: row.id,
        schoolId: this.userInfo.schoolId,
        startTime: row.limitDateTime[0],
        endTime: row.limitDateTime[1]
      };
      setExperimentDateTime(obj)
        .then(res => {
          this.$message.success("修改成功");
          (row.startTime = row.limitDateTime[0]),
            (row.endTime = row.limitDateTime[1]);
        })
        .finally(() => {
          row.editTimeLoading = false;
        });
    },
    //获取列表
    getTableData() {
      this.tableLoading = true;
      let obj = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        userId: this.userInfo.userId
      };
      getAllExperiment(obj)
        .then(res => {
          res.data.forEach(element => {
            element.statusLoading = false;
            element.delLoading = false;
            element.editTimeLoading = false;
          });
          this.tableData = res.data;
          console.log(this.tableData)
          this.total = res.total;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    //预览
    showExperiment(row) {
        this.dialogLoading = true;
        this.dialogVisible = true;
        let experimentId = row.id;
        this.experiment.name = row.name
        getExperimentByexperimentId(experimentId).then((res) => {
          //this.experiment = res.data;
          res.data.requiredQuestions.forEach(element => {
                    element.title+="（必做题）"
              });
              console.log(res.data.requiredQuestions)
          res.data.optionalQuestions.forEach(element => {
                    element.title+="（选做题）"
              });
        this.experiment.questions=res.data.requiredQuestions.concat(res.data.optionalQuestions);
        this.dialogLoading = false;
        })
        console.log(this.experiment.questions);
      },


    //跳转到编辑实验
    editExperiment(row) {
      getExperimentByexperimentId(row.id).then(res => {
        row.optionalQuestions = res.data.optionalQuestions;
        row.requiredQuestions = res.data.requiredQuestions;
      })
      this.$router.push({
        name: "experimentModule/experimentCreate",
        query:{id:row.id},
        params: { data: row }
      });
    },
    //处理页面实验数变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getTableData();
    },
    //处理页面变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getTableData();
    },
   
        // 上移按钮
    sortUp (index, row) {
      if (index === 0 ) {
        this.$message({
          message: '已经是列表中第一个素材！',
          type: 'warning'
        })
      } else {
        let temp = this.tableData[index - 1]
        this.$set(this.tableData, index - 1, this.tableData[index])
        this.$set(this.tableData, index, temp);
        this.comfirmSort();
      }
    },
        // 下移按钮
    sortDown (index, row) {
      if (index === (this.tableData.length - 1)) {
        this.$message({
          message: '已经是列表中最后一个素材！',
          type: 'warning'
        })
      } else {
        let i = this.tableData[index + 1]
        this.$set(this.tableData, index + 1, this.tableData[index]);
        this.$set(this.tableData, index, i);
        this.comfirmSort();
      }
    },
    comfirmSort() {
      var list = Array.from(this.tableData,({id})=>id);
      console.log(list);
      sortExperiment(list,this.userInfo.schoolId).then((res) => {
      this.$message.success("调整顺序成功");
      }).catch(()=>{
      this.$message.error("调整顺序失败");
      }).finally(() => {
      this.sortDialogVisible = false;
      })
      //this.getTableData();
    }
    




  }
};
</script>
<style scoped>
.title {
  font-size: 20px;
  color: #409eff;
  font-weight: bold;
}
.el-table {
  margin-top: 20px;
}
.head {
  position: relative;
}
.sortBtn {
  position: absolute;
  right: 250px;
}
.getBtn {
  position: absolute;
  right: 110px;
}
.refreshBtn{
  position:absolute;
  right:10px;
}
.el-tag.el-tag--light.close
{
  background-color:#fef0f0;
  border-color:#f56c6c;
  color:#f56c6c;
}
.el-tag.el-tag--light.open{
  border-color:#67c23a;
  background-color:#f0f9eb;
  color:#67c23a;
}
.button-bone:hover{
  background:none;
  color:#606266;
}


</style>
